﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Org.SpmisFramework.Net
{
    /// <summary>
    /// Web数据请求
    /// </summary>
    public class WebDataRequest
    {
        /// <summary>
        /// Post方式提交数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string Post(string url, string param, Encoding encoding)
        {
            byte[] postBytes = System.Text.Encoding.ASCII.GetBytes(param);

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Method = "POST";
            //req.KeepAlive = false;
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = postBytes.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(postBytes, 0, postBytes.Length);
            }

            using (WebResponse res = req.GetResponse())
            {
                using (StreamReader sr = new StreamReader(res.GetResponseStream(), encoding))
                {
                    string strResult = sr.ReadToEnd();
                    return strResult;
                }
            }
        }

        /// <summary>
        /// Get方式提交数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string Get(string url, string param, Encoding encoding)
        {
            string address = url + "?" + param;
            Uri uri = new Uri(address);
            WebRequest webReq = WebRequest.Create(uri);

            using (HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse())
            {
                using (Stream respStream = webResp.GetResponseStream())
                {
                    using (StreamReader objReader = new StreamReader(respStream, encoding))
                    {
                        string strRes = objReader.ReadToEnd();
                        return strRes;
                    }
                }
            }
        }
    }
}
